package com.zg.system.auth;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.C;
import com.zg.common.core.R;
import com.zg.common.core.dao.auth.AuthMenu;
import com.zg.common.core.dao.auth.AuthMenuDao;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class MenuController {

    private final AuthMenuDao menuDao;

    @GetMapping("/menu/list")
    public R<?> list() {
        List<AuthMenu> firstList = menuDao.list(
                new LambdaQueryWrapper<AuthMenu>()
                        .eq(AuthMenu::getLayer, 1)
        );
        firstList.stream().forEach(first->{
            List<AuthMenu> secondList = menuDao.list(
                    new LambdaQueryWrapper<AuthMenu>()
                            .eq(AuthMenu::getPid, first.getId())
            );
            first.setChildren(secondList);
        });
        return R.success(firstList);
    }

    @PostMapping("/menu/add")
    public R<?> add(@RequestBody AuthMenu obj) {
        menuDao.save(obj);
        return R.success(obj);
    }

    @PostMapping("/menu/update")
    public R<?> update(@RequestBody AuthMenu obj) {
        AuthMenu old = menuDao.getById(obj.getId());
        BeanUtil.copyProperties(obj, old, C.IGNORED_PROPERTIES);
        menuDao.updateById(old);
        return R.success(old);
    }

    @PostMapping("/menu/del")
    public R<?> del(@RequestBody List<Long> ids) {
        menuDao.removeBatchByIds(ids);
        return R.success();
    }
}
